package demo.jackson.serialize;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;

import demo.jackson.JacksonInterface;
import demo.jackson.Type;
import demo.jackson.impl.Payload;

/**
 *
 */
public class PayloadSerialize extends StdSerializer<Payload> {

    private static final long serialVersionUID = 7679701332948432903L;

    protected PayloadSerialize() {
        this(null);
    }

    protected PayloadSerialize(Class<Payload> t) {
        super(t);
    }

    @Override
    public void serialize(Payload value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        JacksonInterface payload = value.getPayload();
        gen.writeStartObject();
        if (payload != null) {
            Type type = payload.getClass().getAnnotation(Type.class);
            if (type != null) {
                gen.writeStringField("type", type.value());
            }
        }
        gen.writeObjectField("payload", payload);
        gen.writeEndObject();
    }
}
